import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { Router } from 'vue-router';
import { httpReqeustApi } from '/@/api/linxyun/base';
import { InputTypeArray } from '/@/components/Linxyun/custom/DataStructs/commontype';
import EnumOptions from '/@/components/Linxyun/Datas/enum_options.js';
import { LevelDataValid, MainGrpFieldCfg, FieldDataValidDefine } from '../interface';
import { useUserInfo } from '/@/stores/userInfo';
const httpRequest = httpReqeustApi();
const useUserInfoStore = useUserInfo();
import { createDDE_SA } from '/@/utils/stringUtil';

const DDE_SA = createDDE_SA(BASE_API.ENT_CODE || 0, 0, 0);
const headers = { 'DDE-SA': DDE_SA, 'Content-Type': 'application/json;charset=UTF-8' };
/**
 * 获取 PageID
 * @param router
 * @return pageid
 */
export const getReportID = (router: Router) => {
	const ReportID = ref();
	const ReportIDLength = 'ReportID='.length;
	const pathPageIdIdx = router.currentRoute.value.path.indexOf('ReportID=');

	if (pathPageIdIdx < 0) {
		ElMessage({
			message: '页面错误，ErrorCode: 880320',
			type: 'error',
			duration: BASE_API.MSG_SHOW_TIME,
		});
		// 退回到上一个页面。
		router.back();
	}

	let pathPageIdEndIdx = router.currentRoute.value.path.indexOf('&', pathPageIdIdx + 1);
	if (pathPageIdEndIdx <= 0) {
		pathPageIdEndIdx = router.currentRoute.value.path.length;
	}
	console.log('pathPageIdIdx:', pathPageIdIdx, pathPageIdEndIdx);
	const tempReportID = router.currentRoute.value.path.substring(pathPageIdIdx + ReportIDLength, pathPageIdEndIdx);
	console.log('pageId:', tempReportID);
	if (!tempReportID) {
		ElMessage({
			message: '页面错误，ErrorCode: 880320',
			type: 'error',
			duration: BASE_API.MSG_SHOW_TIME,
		});
		// 退回到上一个页面。
		router.back();
	}
	ReportID.value = Number(tempReportID);
	if (isNaN(ReportID.value)) {
		ElMessage({
			message: '页面错误，ErrorCode: 880320',
			type: 'error',
			duration: BASE_API.MSG_SHOW_TIME,
		});
		// 退回到上一个页面。
		router.back();
	}
	console.log('customizetab onMounted pageid: ', ReportID.value);
	return ReportID;
};

/**
 * 查询报表配置
 * @param ReportID
 * @returns
 */
export const queryReportConfigAndFieldDef = async (ReportID: number) => {
	const EntCode = useUserInfoStore.userInfos?.EntCode;
	if (!EntCode) {
		ElMessage({
			message: 'EntCode 为空',
			type: 'error',
			duration: BASE_API.MSG_SHOW_TIME,
		});
		return;
	}
	const data = { ReportID: ReportID, EntCode };
	const res: any = await httpRequest.Post('/eslithe/queryReportDefNew.action', {}, data, headers);
	if (!res.success && res.code !== '0000') {
		ElMessage({
			message: '查询报表配置错误',
			type: 'error',
			duration: BASE_API.MSG_SHOW_TIME,
		});
		return {};
	}
	const ReportDefData: Record<string, any> = res.Records[0] || {};
	ReportDefData.GroupFieldCfg = JSON.parse(ReportDefData.GroupFieldCfg.replace(/\\/g, ''));
	ReportDefData.MainGrpFieldCfg = JSON.parse(ReportDefData.MainGrpFieldCfg.replace(/\\/g, ''));
	console.log('查询报表配置:', ReportDefData);

	const ReportFieldRes: any = await httpRequest.Post('/eslithe/queryReportFieldNew.action', {}, { ReportID: ReportDefData.ReportID }, headers);
	if (!ReportFieldRes.success && ReportFieldRes.code !== '0000') {
		ElMessage({
			message: '查询报表字段定义错误',
			type: 'error',
			duration: BASE_API.MSG_SHOW_TIME,
		});
		return {};
	}
	const ReportFieldData = ReportFieldRes.Records || [];

	// 过滤区域的配置
	const filterDefCfg: Record<string, any>[] = [];
	ReportFieldData.forEach((fc: Record<string, any>) => {
		fc.FilterCfg = JSON.parse(fc.FilterCfg.replace(/\\/g, ''));
		fc.TabShowCfg = JSON.parse(fc.TabShowCfg.replace(/\\/g, ''));

		if (fc.FilterCfg.IsFilter) {
			// 子分组
			const GroupFieldCfg = ReportDefData.GroupFieldCfg;
			for (let i = 0; i < GroupFieldCfg.length; i++) {
				const arr = ['Superior', 'Dimension', 'Child'];
				for (const item of arr) {
					console.log(
						'aaaaaaaaaaaaaaaaaa',
						'GroupFieldCfg:',
						GroupFieldCfg[i][item].Name,
						'rd:',
						fc.FieldName,
						GroupFieldCfg[i][item].seqeOrDataSour.split(',').length > 1
					);
					if (
						GroupFieldCfg[i][item].Name &&
						fc.FieldName === GroupFieldCfg[i][item].Name &&
						GroupFieldCfg[i][item].seqeOrDataSour.split(',').length > 1
					) {
						fc.FilterCfg.InputDefine.EnumValue = GroupFieldCfg[i][item].seqeOrDataSour;
						fc.FilterCfg.InputType = 1;
					}
				}
			}

			const InputType = InputTypeArray[fc.FilterCfg.InputType];
			const newFilterDefCig: Record<string, any> = {
				InputType,
				FieldName: fc.FieldName,
				FilterWidth: fc.FilterCfg.FilterWidth,
				TipsText: fc.FilterCfg.Tips,
				InputDefine: fc.FilterCfg.InputDefine,
				Label: fc.ViewName,
				isReport: true,
			};

			filterDefCfg.push(newFilterDefCig);
		}
	});
	return {
		ReportDefData,
		ReportFieldData,
		filterDefCfg,
	};
};

/**
 * 解析表头配置
 * @param ReportDefData
 * @param ReportFieldData
 * @returns
 */
export const parseTableHeadDef = (ReportDefData: Record<string, any>, ReportFieldData: Record<string, any>) => {
	// let tmpLevelDataValidArray: Record<string, any>[] = [];
	let levelDataValidArray: LevelDataValid[] = [];
	const groupsFields: string[][] = [];
	// const tmpGroupData: Record<string, any>[] = [];
	const mapFieldDataValid: Map<string, FieldDataValidDefine> = new Map();
	let levelNumber = 1;
	// 取出主分组字段配置
	const mainGrpFieldCfg: MainGrpFieldCfg[] = ReportDefData.MainGrpFieldCfg.map((mc: Record<string, any>) => {
		const filedItem = ReportFieldData.find((rd: Record<string, any>) => mc.Field === rd.FieldName);
		let tmpDataList: Record<string, string>[] = [];
		const EnumOption = EnumOptions.instance().getOptions(mc.Field);
		if (EnumOption) {
			tmpDataList = EnumOption.map((e: any) => {
				return { value: e.value + '', name: e.label };
			});
		}
		const item: MainGrpFieldCfg = {
			FieldName: filedItem.FieldName,
			ViewName: filedItem.ViewName,
			ShowColWidth: filedItem.TabShowCfg.ShowColWidth,
			Childs: [],
			DataList: tmpDataList,
			IsTotalCol: false,
			IsTrun: false,
			FieldLevelName: '',
			DataType: InputTypeArray[mc.InputType],
			FormatType: mc.TimeType,
		};
		return item;
	});

	console.log('mainGrpFieldCfg: ', mainGrpFieldCfg);

	// ReportFieldData 报表数据源对应字段的定义
	// 将组主分组过滤掉
	const otherFiled = ReportFieldData.filter((rd: Record<string, any>) => {
		const index = mainGrpFieldCfg.findIndex((mc: Record<string, any>) => mc.value === rd.FieldName);
		return index === -1;
	});

	console.log('otherFiled: ', otherFiled);

	ReportDefData.GroupFieldCfg.forEach((rd: Record<string, any>, rdIndex: number) => {
		// 子分组字段
		const subGroupFields: string[] = [];
		let groupLevelNumber = 0;
		const { Name: DName, seqeOrDataSour: DseqeOrDataSour, isTotal: DIsTotal } = rd.Dimension; // 维度
		const { Name: ParentName, seqeOrDataSour: SseqeOrDataSour, isTotal: ParentIsTotal } = rd.Superior; // 父级
		const { Name: ChildName, seqeOrDataSour: CseqeOrDataSour } = rd.Child; // 子级
		const groupLevelDataValidArr: LevelDataValid[] = [];
		if (ParentName) {
			subGroupFields.push(ParentName);
			groupLevelNumber++;
			const index = otherFiled.findIndex((f: any) => f.FieldName === ParentName);
			// const showIndex = otherFiled[index].TabShowCfg.ShowIndex;
			if (SseqeOrDataSour && rd.IsTrans) {
				const EnumOption = SseqeOrDataSour && SseqeOrDataSour.indexOf(',') === -1 ? EnumOptions.instance().getOptions(SseqeOrDataSour) : null;
				let tmpDataList: Record<string, string>[] = [];
				if (EnumOption) {
					tmpDataList = EnumOption.map((e: any) => {
						return { value: e.value + '', name: e.label };
					});
					// 保存解析好的字段对应的取值序列
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: DName,
						ViewName: otherFiled[index].ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: tmpDataList,
						ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
				} else {
					const arr = SseqeOrDataSour.split(',');
					tmpDataList = arr.map((a: string) => {
						return { value: a, name: a };
					});
					// 保存解析好的字段对应的取值序列
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: DName,
						ViewName: otherFiled[index].ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: tmpDataList,
						ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
				}
				if (tmpDataList.length > 0) {
					tmpDataList.map((a: Record<string, string>) => {
						const levelDataValid: LevelDataValid = {
							FieldName: ParentName,
							FieldLevelName: ParentName + a.value,
							ViewName: a.name,
							ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
							DataList: tmpDataList,
							Childs: [],
							IsTotalCol: false,
							IsTrun: true,
						};
						groupLevelDataValidArr.push(levelDataValid);
					});
				} else {
					// TODO
					// 提示错误，没有解析到字段的序列
				}
			} else {
				const levelDataValid: LevelDataValid = {
					FieldName: ParentName,
					FieldLevelName: ParentName + '' + rdIndex,
					ViewName: otherFiled[index].ViewName,
					ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
					DataList: [],
					Childs: [],
					IsTotalCol: false,
					IsTrun: false,
				};
				groupLevelDataValidArr.push(levelDataValid);
				const tmpFieldDataValid: FieldDataValidDefine = {
					FieldName: levelDataValid.FieldLevelName,
					ViewName: levelDataValid.ViewName,
					IsDimension: true,
					NeedTrun: false,
					DataList: [],
					ShowColWidth: levelDataValid.ShowColWidth,
					NeedSum: false,
				};
				mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
			}
		}
		if (DName) {
			subGroupFields.push(DName);
			groupLevelNumber++;
			const index = otherFiled.findIndex((f: any) => f.FieldName === DName);
			// const showIndex = otherFiled[index].TabShowCfg.ShowIndex;
			// 转成竖表的情况处理
			if (DseqeOrDataSour && rd.IsTrans) {
				console.log('DseqeOrDataSour', DseqeOrDataSour);
				const EnumOption = DseqeOrDataSour && DseqeOrDataSour.indexOf(',') === -1 ? EnumOptions.instance().getOptions(DseqeOrDataSour) : null;
				if (EnumOption) {
					const tmpDataList = EnumOption.map((e: any) => {
						return { value: e.value + '', name: e.label };
					});
					// 保存解析好的字段对应的取值序列
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: DName,
						ViewName: otherFiled[index].ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: tmpDataList,
						ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
					if (tmpDataList.length > 0) {
						createGroupDataValid(DName, groupLevelDataValidArr, tmpDataList, otherFiled[index].TabShowCfg.ShowColWidth + 0 || 0, '');
					} else {
						// TODO
						// 提示错误，没有解析到字段的序列
					}
				} else {
					const arr = DseqeOrDataSour.split(',');
					console.log('arr SseqeOrDataSour', arr);
					const tmpDataList = arr.map((a: string) => {
						return { value: a, name: a };
					});
					// 保存解析好的字段对应的取值序列
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: DName,
						ViewName: otherFiled[index].ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: tmpDataList,
						ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
					if (tmpDataList.length > 0) {
						createGroupDataValid(DName, groupLevelDataValidArr, tmpDataList, otherFiled[index].TabShowCfg.ShowColWidth + 0 || 0, '');
					} else {
						// TODO
						// 提示错误，没有解析到字段的序列
					}
				}
				console.log('groupLevelDataValidArr: ', groupLevelDataValidArr);
			} else {
				const levelDataValid: LevelDataValid = {
					FieldName: DName,
					FieldLevelName: DName + '' + rdIndex,
					ViewName: otherFiled[index].ViewName,
					ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
					DataList: [],
					Childs: [],
					IsTotalCol: false,
					IsTrun: false,
				};
				groupLevelDataValidArr.push(levelDataValid);
				const tmpFieldDataValid: FieldDataValidDefine = {
					FieldName: levelDataValid.FieldLevelName,
					ViewName: levelDataValid.ViewName,
					IsDimension: true,
					NeedTrun: false,
					DataList: [],
					ShowColWidth: levelDataValid.ShowColWidth,
					NeedSum: false,
				};
				mapFieldDataValid.set(levelDataValid.FieldLevelName, tmpFieldDataValid);
			}
		}
		if (ChildName) {
			subGroupFields.push(ChildName);
			groupLevelNumber++;
			const index = otherFiled.findIndex((f: any) => f.FieldName === ChildName);
			// const showIndex = otherFiled[index].TabShowCfg.ShowIndex;
			if (CseqeOrDataSour && CseqeOrDataSour && rd.IsTrans) {
				const EnumOption = CseqeOrDataSour && CseqeOrDataSour.indexOf(',') === -1 ? EnumOptions.instance().getOptions(CseqeOrDataSour) : null;
				if (EnumOption) {
					const tmpDataList = EnumOption.map((e: any) => {
						return { value: e.value + '', name: e.label };
					});
					// 保存解析好的字段对应的取值序列
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: ChildName,
						ViewName: otherFiled[index].ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: tmpDataList,
						ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
					if (tmpDataList.length > 0) {
						createGroupDataValid(ChildName, groupLevelDataValidArr, tmpDataList, otherFiled[index].TabShowCfg.ShowColWidth + 0 || 0, '');
					} else {
						// TODO
						// 提示错误，没有解析到字段的序列
					}
				} else {
					const arr = CseqeOrDataSour.split(',');
					const tmpDataList = arr.map((a: string) => {
						return { value: a, name: a };
					});
					// 保存解析好的字段对应的取值序列
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: ChildName,
						ViewName: otherFiled[index].ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: tmpDataList,
						ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
					if (tmpDataList.length > 0) {
						createGroupDataValid(ChildName, groupLevelDataValidArr, tmpDataList, otherFiled[index].TabShowCfg.ShowColWidth + 0 || 0, '');
					} else {
						// TODO
						// 提示错误，没有解析到字段的序列
					}
				}
				console.log('groupLevelDataValidArr: ', groupLevelDataValidArr);
			} else {
				const levelDataValid: LevelDataValid = {
					FieldName: ChildName,
					FieldLevelName: ChildName + '' + rdIndex,
					ViewName: otherFiled[index].ViewName,
					ShowColWidth: otherFiled[index].TabShowCfg.ShowColWidth,
					DataList: [],
					Childs: [],
					IsTotalCol: false,
					IsTrun: false,
				};
				groupLevelDataValidArr.push(levelDataValid);
				const tmpFieldDataValid: FieldDataValidDefine = {
					FieldName: levelDataValid.FieldLevelName,
					ViewName: levelDataValid.ViewName,
					IsDimension: true,
					NeedTrun: false,
					DataList: [],
					ShowColWidth: levelDataValid.ShowColWidth,
					NeedSum: false,
				};
				mapFieldDataValid.set(levelDataValid.FieldLevelName, tmpFieldDataValid);
			}
		}

		// 是否横向
		if (rd.IsTrans) {
			// 橫向时增加列Total列
			createTotalDataValid(ParentIsTotal, DIsTotal, groupLevelNumber, groupLevelDataValidArr);
		} else {
			const levelDataValid: LevelDataValid = {
				FieldName: 'Total' + rdIndex,
				FieldLevelName: 'Total' + rdIndex,
				ViewName: '数量',
				ShowColWidth: 100,
				DataList: [],
				Childs: [],
				IsTotalCol: true,
				IsTrun: false,
			};
			groupLevelDataValidArr.push(levelDataValid);
			const tmpFieldDataValid: FieldDataValidDefine = {
				FieldName: levelDataValid.FieldLevelName,
				ViewName: levelDataValid.ViewName,
				IsDimension: true,
				NeedTrun: false,
				DataList: [],
				ShowColWidth: levelDataValid.ShowColWidth,
				NeedSum: true,
			};
			mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
		}
		levelDataValidArray.push(...groupLevelDataValidArr);
		groupsFields.push(subGroupFields);
	});

	// 增加分组Total
	function createTotalDataValid(partentNeedTotal: boolean, dNeedTotal: boolean, level: number, groupLevelDataValidArr: LevelDataValid[]) {
		console.log('groupLevelDataValidArr level', level);
		if (level > 2) {
			groupLevelDataValidArr.forEach((item) => {
				if (partentNeedTotal) {
					const pChildDataValid: LevelDataValid = {
						FieldName: item.FieldName,
						FieldLevelName: item.FieldLevelName + 'Total',
						ViewName: '合计',
						ShowColWidth: item.ShowColWidth,
						DataList: [],
						Childs: [],
						IsTotalCol: true,
						IsTrun: true,
					};
					item.Childs.push(pChildDataValid);
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: pChildDataValid.FieldLevelName,
						ViewName: pChildDataValid.ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: [],
						ShowColWidth: pChildDataValid.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
				}
				if (dNeedTotal) {
					item.Childs.forEach((childItem) => {
						if (childItem.FieldLevelName.lastIndexOf('Total') + 'Total'.length !== childItem.FieldLevelName.length) {
							const dChildDataValid: LevelDataValid = {
								FieldName: childItem.FieldName,
								FieldLevelName: childItem.FieldLevelName + 'Total',
								ViewName: '合计',
								ShowColWidth: item.ShowColWidth,
								DataList: [],
								Childs: [],
								IsTotalCol: true,
								IsTrun: true,
							};
							console.log('dChildDataValid FieldLevelName', dChildDataValid.FieldLevelName);
							childItem.Childs.push(dChildDataValid);
							const tmpFieldDataValid: FieldDataValidDefine = {
								FieldName: dChildDataValid.FieldLevelName,
								ViewName: dChildDataValid.ViewName,
								IsDimension: true,
								NeedTrun: true,
								DataList: [],
								ShowColWidth: dChildDataValid.ShowColWidth,
								NeedSum: true,
							};
							mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
						}
					});
				}
			});
		}

		if (level === 2) {
			if (partentNeedTotal || dNeedTotal) {
				groupLevelDataValidArr.forEach((item) => {
					const pChildDataValid: LevelDataValid = {
						FieldName: item.FieldName,
						FieldLevelName: item.FieldLevelName + 'Total',
						ViewName: '合计',
						ShowColWidth: item.ShowColWidth,
						DataList: [],
						Childs: [],
						IsTotalCol: true,
						IsTrun: true,
					};
					item.Childs.push(pChildDataValid);
					const tmpFieldDataValid: FieldDataValidDefine = {
						FieldName: pChildDataValid.FieldLevelName,
						ViewName: pChildDataValid.ViewName,
						IsDimension: true,
						NeedTrun: true,
						DataList: [],
						ShowColWidth: pChildDataValid.ShowColWidth,
						NeedSum: true,
					};
					mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
				});
			}
		}
	}

	function createGroupDataValid(
		fieldName: string,
		groupDataValid: LevelDataValid[],
		currentDataValid: Record<string, string>[],
		showColWidth: number,
		parentLevelName: string
	) {
		// 已经存在
		if (groupDataValid && groupDataValid.length > 0) {
			groupDataValid.forEach((item: LevelDataValid) => {
				// 如何当前节点不是统计就递归
				createGroupDataValid(fieldName, item.Childs, currentDataValid, showColWidth, item.FieldLevelName);
			});
		} else {
			currentDataValid.forEach((item) => {
				const childDataValid: LevelDataValid = {
					FieldName: fieldName,
					FieldLevelName: parentLevelName + fieldName + item.value,
					ViewName: item.name,
					ShowColWidth: showColWidth,
					DataList: currentDataValid,
					Childs: [],
					IsTotalCol: true,
					IsTrun: true,
				};
				groupDataValid.push(childDataValid);
				const tmpFieldDataValid: FieldDataValidDefine = {
					FieldName: childDataValid.FieldLevelName,
					ViewName: item.name,
					IsDimension: true,
					NeedTrun: true,
					DataList: currentDataValid,
					ShowColWidth: showColWidth,
					NeedSum: true,
				};
				mapFieldDataValid.set(tmpFieldDataValid.FieldName, tmpFieldDataValid);
			});
			return;
		}
	}

	// 去除参与分组统计的字段
	let tmpOtherField = otherFiled.map((item: Record<string, any>) => ({
		value: item.FieldName,
		name: item.ViewName,
		showIndex: item.TabShowCfg.ShowIndex,
		ShowColWidth: item.TabShowCfg.ShowColWidth,
	}));
	groupsFields.forEach((groupItem) => {
		groupItem.forEach((item) => {
			const tmpFields = tmpOtherField.filter((x: Record<string, any>) => x.value !== item);
			tmpOtherField = tmpFields;
		});
	});

	console.log('levelDataValidArray: ', levelDataValidArray);
	return {
		mainGrpFieldCfg,
		levelNumber,
		levelDataValidArray,
		groupsFields,
		mapFieldDataValid,
		otherFields: tmpOtherField.sort(compare('showIndex')),
	};
};

/**
 * 查询分组数据
 * @param GroupFieldCfg
 * @param MainGrpFieldCfg
 * @param groupsFields
 * @param mapFieldDataValid
 * @param mapFieldDataValid
 * @param queryParams
 * @returns
 */
export const queryGroupData = (
	GroupFieldCfg: Record<string, any>,
	MainGrpFieldCfg: Record<string, any>,
	// tmpGroupData: Record<string, any>,
	groupsFields: string[][],
	mapFieldDataValid: Map<string, FieldDataValidDefine>,
	levelDataValidArray: LevelDataValid[],
	queryParams: Record<string, any> = {
		current: 1,
		limit: 300,
	}
) => {
	console.log('MainGrpFieldCfg', MainGrpFieldCfg);
	const totalSize = ref<number>(0);
	// const statResults = reactive<Record<string, any>>({ data: [] });
	const tableData = reactive<Record<string, any>>({ data: [] });
	const statDatas: any = {};
	GroupFieldCfg.forEach((item: Record<string, any>, groupIndex: number) => {
		httpRequest.Post(item.Interface, {}, queryParams).then((res: any) => {
			if (res.code === '0000' && res.success) {
				// 转数值型
				totalSize.value = res.TotalSize * 1;
				console.log('httpRequest Records', item.Interface, res.Records);
				res.Records.map((record: Record<string, any>) => {
					let newRecord: Record<string, any> = { ...record };
					console.log('88888', newRecord, item.Superior.Name);
					let statDataKey = '';
					MainGrpFieldCfg.forEach((mainGrpItem: Record<string, any>) => {
						// 处理时间字段
						if (mainGrpItem.FormatType) {
							statDataKey += formatTime(record[mainGrpItem.FieldName], mainGrpItem.FormatType);
							newRecord[mainGrpItem.FieldName] = formatTime(record[mainGrpItem.FieldName], mainGrpItem.FormatType);
						} else if (mainGrpItem.DataList?.length > 0) {
							// 枚举
							statDataKey += record[mainGrpItem.FieldName];

							if (record[mainGrpItem.FieldName]) {
								const value = mainGrpItem.DataList.find((d: { value: string | number; label: string }) => d.value === record[mainGrpItem.FieldName]);
								newRecord[mainGrpItem.FieldName] = value;
							}
						} else {
							// 非时间字段
							statDataKey += record[mainGrpItem.FieldName];
							newRecord[mainGrpItem.FieldName] = record[mainGrpItem.FieldName];
						}
					});
					console.log('statDataKey:', statDataKey);
					let currentRecord: Record<string, any> = statDatas[statDataKey];

					if (!currentRecord) {
						currentRecord = { ...record };

						MainGrpFieldCfg.forEach((mainGrpItem: Record<string, any>) => {
							// 处理时间字段
							if (mainGrpItem.FormatType) {
								currentRecord[mainGrpItem.FieldName] = formatTime(record[mainGrpItem.FieldName], mainGrpItem.FormatType);
							} else if (mainGrpItem.DataList?.length) {
								// 枚举
								statDataKey += record[mainGrpItem.FieldName];

								if (record[mainGrpItem.FieldName]) {
									const value = mainGrpItem.DataList.find(
										(d: { value: string | number; label: string }) => d.value === record[mainGrpItem.FieldName]
									);
									newRecord[mainGrpItem.FieldName] = value;
								}
							} else {
								// 非时间字段
								currentRecord[mainGrpItem.FieldName] = record[mainGrpItem.FieldName];
							}
						});

						currentRecord.RecordTotal = 0;
						statDatas[statDataKey] = currentRecord;
					}

					// 横向
					if (item.IsTrans) {
						let subGroupKey = '';
						let totalKeys: string[] = [];
						console.log('groupsFields[groupIndex]', groupsFields[groupIndex]);
						groupsFields[groupIndex].forEach((item, idx) => {
							subGroupKey += item + record[item];

							if (idx === 0) {
								const totalKey = item + record[item] + 'Total';
								totalKeys.push(totalKey);
							}
							if (idx === 1) {
								const reg = new RegExp('Total');
								const prefix = totalKeys[0].replace(reg, '');
								const totalKey = prefix + item + record[item] + 'Total';
								totalKeys.push(totalKey);
							}
						});
						console.log('subGroupKey', subGroupKey);
						let val = 0;
						// 全部总计
						if (item.CountType === 'total') {
							// * 1转数值
							val = record[item.TotalField] * 1;
						} else if (item.CountType === 'row') {
							// 全部总量
							const count = parseInt(record.Count);
							if (isNaN(count)) {
								val = 0;
							} else {
								val = count;
							}
						}

						if (groupIndex == 0) {
							currentRecord.RecordTotal += val;
						}

						const tmpFieldVal = currentRecord[subGroupKey];
						if (tmpFieldVal) {
							currentRecord[subGroupKey] += val;
						} else {
							currentRecord[subGroupKey] = val;
						}

						// 把分组下的合计计算出来
						totalKeys.forEach((item) => {
							let fieldTotal = currentRecord[item];
							if (fieldTotal) {
								fieldTotal += val;
							} else {
								fieldTotal = val;
							}
							currentRecord[item] = fieldTotal;
						});
					} else {
						let val = 0;
						// 合计
						if (item.CountType === 'total') {
							const subGroupTotal = record[item.TotalField];
							if (isNaN(parseInt(subGroupTotal))) {
								val = 0;
							} else {
								val = subGroupTotal;
							}
							console.log('no IsTrans subGroupTotal:', subGroupTotal);
						} else if (item.CountType === 'row') {
							const subGroupTotal = record.Count;
							if (isNaN(parseInt(subGroupTotal))) {
								val = 0;
							} else {
								val = subGroupTotal;
							}
							console.log('数量:', subGroupTotal);
						}
						console.log('currentRecord', { ...statDatas[statDataKey] }, MainGrpFieldCfg);
						// 分组字段重命名了,解决同一字段出现在不同的统计维度里面
						groupsFields[groupIndex].forEach((item) => {
							currentRecord[item + groupIndex] = getEnumVal(item, statDatas[statDataKey][item]);
						});
						console.log();
						// 分组总数
						currentRecord['Total' + groupIndex] &&= currentRecord['Total' + groupIndex] * 1 + val * 1;
						currentRecord['Total' + groupIndex] ||= val * 1;
						// 是否累计总计 为0时直接赋值为总计
						if (groupIndex === 0) {
							currentRecord.RecordTotal += val;
						}
					}
				});
				tableData.data = [];
				const vals = Object.values(statDatas);
				console.log('vals: ', vals, statDatas);
				tableData.data.push(...vals);
			}
		});
	});
	function getEnumVal(enumKey: string, val: string) {
		const EnumOption = EnumOptions.instance().getOptions(enumKey);
		console.log('getEnumVal EnumOption', EnumOption);
		if (EnumOption?.length) {
			return EnumOption.find((e: { value: string; label: string }) => e.value === val)?.label || val;
		} else {
			return val;
		}
	}
	console.log('statResults', statDatas);
	return { tableData, totalSize };
};

/**
 * 处理分页操作
 * @param ReportDefData
 * @param tmpGroupData
 * @param tableData
 * @returns
 */
export const handlerPagination = (
	ReportDefData: Record<string, any>,
	tableData: Record<string, any>,
	groupsFields: string[][],
	mapFieldDataValid: Map<string, FieldDataValidDefine>,
	levelDataValidArray: LevelDataValid[]
) => {
	const pageConfig = reactive({
		sizes: [100, 200, 300, 400],
		layout: 'total, sizes, prev, pager, next, jumper',
		total: 0,
		pagesize: 300,
		pageShow: true,
		currentPage: 1,
	});

	const handleSizeChange = (size: number) => {
		console.log('更改每页条数');
		const { tableData: newTableData } = queryGroupData(
			ReportDefData.GroupFieldCfg,
			ReportDefData.MainGrpFieldCfg,
			groupsFields,
			mapFieldDataValid,
			levelDataValidArray,
			{
				current: pageConfig.currentPage,
				limit: size,
			}
		);
		console.log('newTableData', newTableData.data);
		watchEffect(() => {
			tableData.data = newTableData.data;
		});
	};
	const handleCurrentChange = (currentPage: number) => {
		console.log('更改当前页时触发', currentPage);
		const { tableData: newTableData } = queryGroupData(
			ReportDefData.GroupFieldCfg,
			ReportDefData.MainGrpFieldCfg,
			groupsFields,
			mapFieldDataValid,
			levelDataValidArray,
			{
				current: currentPage,
				limit: pageConfig.pagesize,
			}
		);
		console.log('newTableData', newTableData.data);
		watchEffect(() => {
			tableData.data = newTableData.data;
		});
	};
	return { pageConfig, handleSizeChange, handleCurrentChange };
};
/**
 * 通过对象中某个的值继续排序时用
 * mpLevelDataValidArray.sort(compare('showIndex'))
 * @param property
 * @returns
 */
const compare = (property: string) => {
	return function (a: any, b: any) {
		var value1 = a[property];
		var value2 = b[property];
		return value1 - value2;
	};
};

// 格式化时间
const formatTime = (time: string, type: string) => {
	let newTime = '';
	if (!time) {
		return '';
	}
	switch (type) {
		case 'year':
			newTime = time;
			break;
		case 'month':
			newTime = (time || '').slice(0, 4) + '-' + (time || '').slice(4, 6);
			break;
		case 'day':
			newTime = (time || '').slice(0, 4) + '-' + (time || '').slice(4, 6) + '-' + (time || '').slice(6, 8);
			break;
		case 'hour':
			newTime = (time || '').slice(0, 4) + '-' + (time || '').slice(4, 6) + '-' + (time || '').slice(6, 8) + ' ' + (time || '').slice(8, 10);
			break;
		case 'minute':
			newTime =
				(time || '').slice(0, 4) +
				'-' +
				(time || '').slice(4, 6) +
				'-' +
				(time || '').slice(6, 8) +
				' ' +
				(time || '').slice(8, 10) +
				':' +
				(time || '').slice(10, 12);
			break;
		case 'second':
			newTime =
				(time || '').slice(0, 4) +
				'-' +
				(time || '').slice(4, 6) +
				'-' +
				(time || '').slice(6, 8) +
				' ' +
				(time || '').slice(8, 10) +
				':' +
				(time || '').slice(10, 12) +
				':' +
				(time || '').slice(12, 14);
			break;
	}
	return newTime;
};
